package com.gui.juc.pool;

import cn.hutool.core.util.RandomUtil;
import com.gui.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ThreadPoolDemo1 {

    public static void main(String[] args) {
        /**
         corePoolSize: 核心线程数个数
         maximumPoolSize: 最大线程数个数
         keepAliveTime: 临时线程最大存活时间
         TimeUnit unit: 临时线程最大存活时间的时间单位
         BlockingQueue<Runnable> workQueue: 阻塞队列
         ThreadFactory: 线程工厂，可以给线程起个名字
         RejectedExecutionHandler handler: 拒绝策略，可以抛出异常 丢弃任务等
         **/

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                3, 5, 1, TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(100),
                new ImportThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        for (int i = 0; i < 150; i++) {
            executor.execute(new ImportData(String.format("" + (i + 1))));
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
            Sleeper.sleep(TimeUnit.MILLISECONDS, 10);
        }
        log.info("线程池执行完毕...");
    }


    private static class ImportData implements Runnable {

        private String message;

        public ImportData(String message) {
            this.message = message;
        }

        @Override
        public void run() {
            log.info("开始第【{}】个执行任务...", message);
            Sleeper.sleep(TimeUnit.SECONDS, 1);
            log.warn("第【{}】个任务执行完成...", message);
        }
    }

    static class ImportThreadFactory implements ThreadFactory {
        AtomicInteger atomicInteger = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("Import-thread-" + atomicInteger.getAndIncrement());
            return thread;
        }
    }
}
